package com.ste.client;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Logger;

public class Connector {
	private Thread readServer;
	private Thread writeServer;
	private Socket socket;

	private View view;
	private static Logger log = Logger.getLogger(Connector.class.getName());

	public Connector(View view) {
		this.view = view;
	}

	public void connect(String ipAddress, String port) {
		try {
			socket = new Socket(ipAddress, Integer.valueOf(port));
			readServer = new Thread(new ReadServer(socket.getInputStream(), view));
			writeServer = new Thread(new WriteServer(socket.getOutputStream(), view));
			start();
			log.info("Connected to server");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		view.getCommandsHandler().setClientName(null);
		if (socket != null && !socket.isClosed()) {
			try {
				socket.close();
			} catch (IOException e) {
			}
		}
	}

	private void start() {
		readServer.start();
		writeServer.start();
		log.info("Client threads started");
	}
}
